#include "db_mysql.h"

///переменные mysql
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char * db_host = "localhost";
char * db_user = "gpslog";
char * db_pass = "gpslog"; /* set me first */
char * db_name = "gpslog";
unsigned short db_port = 0; 
pthread_t db_tid = -1;
volatile char f_stop_db_thread = 0;


/**
 * Функция подключения к БД
 */
static void db_connect()
{
    log_message(LOG_FILE, "connecting to DB server");

    conn = mysql_init(NULL);
    /* Connect to database */
    if (!mysql_real_connect(conn, db_host, db_user, db_pass, db_name, 0, NULL, 0)) 
    {
        log_message(LOG_FILE, mysql_error(conn));
        exit(1);
    }
}

static void db_shutdown()
{
    log_message(LOG_FILE, "closing DB connection");
    /* close connection */
    mysql_close(conn);
}

static void * db_thread(void *params)
{
    while(1)
    {
        sleep(10);
        /* send SQL query */
        if (mysql_query(conn, "show tables")) 
        {
            log_message(LOG_FILE, mysql_error(conn));
            continue;
        }
        res = mysql_use_result(conn);
        /* output table name */
        log_message(LOG_FILE, "MySQL Tables in mysql database:\n");
        while ((row = mysql_fetch_row(res)) != NULL)
        {
            log_message (LOG_FILE, row[0]);
        }
        mysql_free_result(res);
        if (f_stop_db_thread) return NULL;
    }
    return NULL;
}

void start_db_thread()
{
    log_message(LOG_FILE, "NOTE: starting DB thread");
    db_connect();
    pthread_create(&db_tid, NULL, &db_thread, NULL);
    f_stop_db_thread = 1;
}
void stop_db_thread()
{
    f_stop_db_thread = 1;
    pthread_join(db_tid, NULL);
    db_shutdown();
}
